import { computed, unref, watch, type Ref } from 'vue';
import { FormActionType } from '@/components/Form';
import { getModalFormSchemas } from '../datas/roleDrawerData';
import { Role } from '@/api/system/model/roleModel';
import { create, update } from '@/api/system/role';
import { unset } from 'lodash-es';

interface UseRoleFormContext {
  roleRef: Ref<Nullable<Role>>;
  formElRef: Ref<Nullable<FormActionType>>;
}

export function useRoleDrawer({ roleRef, formElRef }: UseRoleFormContext) {
  const formTitle = computed(() => {
    // unref: 返回ref内部值
    return unref(roleRef)?.id ? '编辑' : '新增';
  });

  const formSchemas = computed(() => {
    return [...getModalFormSchemas];
  });

  // CreateRole | UpdateRole
  async function handleSubmit(input) {
    const id = input?.id;
    input['menu_ids'] = input['menu']?.join(',');
    unset(input, 'menu');
    unset(input, 'id');
    const { code, message } = id ? await update(id, input) : await create(input);
    return !code ? Promise.resolve() : Promise.reject(message);
  }

  watch(
    () => unref(roleRef),
    (role) => {
      const formEl = unref(formElRef);
      formEl?.resetFields();
      if (role) {
        formEl?.setFieldsValue(role!);
      }
    },
    {
      immediate: true,
    },
  );

  return {
    formTitle,
    formSchemas,
    handleSubmit,
  };
}
